package com.dayu.sale.service.impl;

import java.math.BigDecimal;
import java.util.*;

import com.dayu.common.core.domain.entity.SysRole;
import com.dayu.common.core.domain.entity.SysUser;
import com.dayu.common.utils.DateUtils;
import com.dayu.common.utils.SecurityUtils;
import com.dayu.recovery.domain.constant.GoodsConstant;
import com.dayu.recovery.mapper.RecoveryGoodsMapper;
import com.dayu.recovery.mapper.RecoveryPartsMapper;
import com.dayu.sale.domain.DySaleGoods;
import com.dayu.sale.domain.DySaleParts;
import com.dayu.sale.domain.vo.SaleGoodsExport;
import com.dayu.sale.mapper.DySaleGoodsMapper;
import com.dayu.sale.mapper.DySalePartsMapper;
import com.dayu.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dayu.sale.mapper.DyBillInfoMapper;
import com.dayu.sale.domain.DyBillInfo;
import com.dayu.sale.service.IDyBillInfoService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

/**
 * 版本3 --- 账单主Service业务层处理
 *
 * @author HK
 * @date 2024-01-10
 */
@Service
public class DyBillInfoServiceImpl implements IDyBillInfoService
{
    @Resource
    private DyBillInfoMapper dyBillInfoMapper;

    @Resource
    private RecoveryGoodsMapper recoveryGoodsMapper;

    @Resource
    private DySaleGoodsMapper saleGoodsMapper;

    @Resource
    private RecoveryPartsMapper recoveryPartsMapper;

    @Resource
    private DySalePartsMapper salePartsMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 查询版本3 --- 账单主
     *
     * @param id 版本3 --- 账单主ID
     * @return 版本3 --- 账单主
     */
    @Override
    public DyBillInfo selectDyBillInfoById(Long id)
    {
        DyBillInfo info = dyBillInfoMapper.selectDyBillInfoById(id);
        DySaleGoods goods = new DySaleGoods();
        goods.setBillId(id);
        info.setGoodsList(saleGoodsMapper.selectDySaleGoodsList(goods));
        DySaleParts parts = new DySaleParts();
        parts.setBillId(id);
        info.setPartsList(salePartsMapper.selectDySalePartsList(parts));
        return info;
    }

    /**
     * 查询版本3 --- 账单主列表
     *
     * @param dyBillInfo 版本3 --- 账单主
     * @return 版本3 --- 账单主
     */
    @Override
    public List<DyBillInfo> selectDyBillInfoList(DyBillInfo dyBillInfo)
    {
        List<SysRole> roles = SecurityUtils.getLoginUser().getUser().getRoles();
        Map<String, Object> map = ObjectUtils.isEmpty(dyBillInfo.getParams()) ? new HashMap<>() : dyBillInfo.getParams();
        for (SysRole r : roles) {
            if(Objects.equals(r.getRoleKey(), "sales")) {
                //权限字段
                dyBillInfo.setSaleUserId(SecurityUtils.getLoginUser().getUser().getUserId());
                //2,592,000,000
                long newTime = System.currentTimeMillis();
                long oldTime = newTime - 2592000000L; //30天前
                map.put("startTime", new Date(oldTime));
                map.put("endTime", new Date(newTime));
            }
        }
        dyBillInfo.setParams(map);
        return dyBillInfoMapper.selectDyBillInfoList(dyBillInfo);
    }

    @Override
    public List<SaleGoodsExport> queryBillExport(DyBillInfo dyBillInfo) {
        List<SaleGoodsExport> list = dyBillInfoMapper.queryBillExport(dyBillInfo);
        list.forEach(item -> {
            BigDecimal sale = ObjectUtils.isEmpty(item.getSalePrice()) ? new BigDecimal(0) : item.getSalePrice();
            BigDecimal cost = ObjectUtils.isEmpty(item.getCostPrice()) ? new BigDecimal(0) : item.getCostPrice();
            BigDecimal freight = ObjectUtils.isEmpty(item.getFreight()) ? new BigDecimal(0) : item.getFreight();
            item.setProfit(sale.subtract(cost).subtract(freight));
            if(!ObjectUtils.isEmpty(item.getOfferName())) {
                Long userId = Long.parseLong(item.getOfferName());
                SysUser user = sysUserMapper.selectUserById(userId);
                if(!ObjectUtils.isEmpty(user))
                    item.setOfferName(user.getNickName());
            }
        });
        return list;
    }

    @Override
    public Map<String, Object> selectDyBillInfoListData(DyBillInfo dyBillInfo) {
        List<DyBillInfo> list = dyBillInfoMapper.selectDyBillInfoList(dyBillInfo);
        BigDecimal cost = new BigDecimal(0);    //成本
        BigDecimal yf = new BigDecimal(0);      //运费
        BigDecimal parts = new BigDecimal(0);   //配件
        BigDecimal lr = new BigDecimal(0);      //利润
        BigDecimal sale = new BigDecimal(0);      //销售

        for (DyBillInfo info : list) {
            cost = cost.add(info.getCostPrice());
            yf = yf.add(info.getFreight());
            parts = parts.add(info.getAccCostPrice());
            lr = lr.add(info.getProfitPrice());
            sale = sale.add(info.getSalePrice());
        }

        Map<String, Object> map = new HashMap<>();
        map.put("cost", cost);
        map.put("yf", yf);
        map.put("parts", parts);
        map.put("lr", lr);
        map.put("sale", sale);
        return map;
    }

    /**
     * 新增版本3 --- 账单主
     *
     * @param bo 版本3 --- 账单主
     * @return 结果
     */
    @Override
    @Transactional
    public int insertDyBillInfo(DyBillInfo bo)
    {
        bo.setCreateBy(SecurityUtils.getUsername()); //创建人
        bo.setCreateTime(DateUtils.getNowDate());
        //计算利润
        BigDecimal p = bo.getSalePrice().subtract(bo.getCostPrice());
        if(!ObjectUtils.isEmpty(bo.getAccCostPrice()))
            p = p.subtract(bo.getAccCostPrice());
        if(!ObjectUtils.isEmpty(bo.getFreight()))
            p = p.subtract(bo.getFreight());
        bo.setProfitPrice(p);
        bo.setStatus(1);
        int num = dyBillInfoMapper.insertDyBillInfo(bo);
        if(num > 0) {
            saleGoodsByList(bo.getGoodsList(), bo.getId());
            salePartsByList(bo.getPartsList(), bo.getId());
        }
        return num;
    }

    /** 添加销售商品*/
    private void saleGoodsByList(List<DySaleGoods> list, Long billId) {
        List<String> goodsIds = new ArrayList<>();
        list.forEach(it -> {
            it.setBillId(billId);
            goodsIds.add(it.getGoodsId());
        });
        //验证是否包含已经出售的商品
        int num = recoveryGoodsMapper.validGoodsSale(goodsIds);
        System.out.println("当前不正常状态商品: " +  num);
        if(num > 0) {
            throw new RuntimeException("出售单中包含" + num + "个商品不可出售！");
        }
        //设置商品为出售
        recoveryGoodsMapper.editGoodsStatusByList(goodsIds, GoodsConstant.GOODS_STATUS_SALE);
        saleGoodsMapper.addSaleGoodsByList(list);
    }

    private void salePartsByList(List<DySaleParts> list, long billId) {
        if(ObjectUtils.isEmpty(list) || list.isEmpty())
            return;
        list.forEach(it -> {
            it.setBillId(billId);
            recoveryPartsMapper.subPartsNoById(it.getPartsId(), it.getPartsNumber());
        });

        salePartsMapper.addPartsByList(list);
    }

    @Override
    public int billPass(Long id,String remark) {
        DyBillInfo info = dyBillInfoMapper.selectDyBillInfoById(id);
        if(ObjectUtils.isEmpty(info))
            throw new RuntimeException("没有获取到详细信息");

        info.setCheckUserId(SecurityUtils.getLoginUser().getUser().getUserId());
        info.setCheckUserName(SecurityUtils.getLoginUser().getUser().getNickName());
        info.setCheckTime(new Date());
        info.setStatus(2); //通过
        info.setUpdateBy(SecurityUtils.getUsername());
        info.setUpdateTime(new Date());
        info.setCheckRemark(remark);
        return dyBillInfoMapper.updateDyBillInfo(info);
    }

    @Override
    @Transactional
    public int billNoPass(Long id,String remark) {
        DyBillInfo info = selectDyBillInfoById(id);
        if(ObjectUtils.isEmpty(info))
            throw new RuntimeException("没有获取到详细信息");

        info.setCheckUserId(SecurityUtils.getLoginUser().getUser().getUserId());
        info.setCheckUserName(SecurityUtils.getLoginUser().getUser().getNickName());
        info.setCheckTime(new Date());
        info.setStatus(3); //通过
        info.setUpdateBy(SecurityUtils.getUsername());
        info.setUpdateTime(new Date());
        info.setCheckRemark(remark);
        //商品回滚
        noPassGoods(info.getGoodsList());
        //配件数量恢复
        if(!ObjectUtils.isEmpty(info.getPartsList()) && !info.getPartsList().isEmpty()) {
            info.getPartsList().forEach(it -> recoveryPartsMapper.addPartsNoById(it.getPartsId(), it.getPartsNumber()));

        }
        return dyBillInfoMapper.updateDyBillInfo(info);
    }

    //将商品恢复正常状态
    public void noPassGoods(List<DySaleGoods> list) {
        List<String> goodsIds = new ArrayList<>();
        list.forEach(it -> {
            goodsIds.add(it.getGoodsId());
        });
        recoveryGoodsMapper.editGoodsStatusByList(goodsIds, GoodsConstant.GOODS_STATUS_OK);
    }
}
